package com.estagio.dao;

import java.util.List;

import org.hibernate.Session;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import util.HibernateUtil;

import com.estagio.entity.Matricula;

public class MatriculaDao extends Dao<Matricula>{

	private Session sessao;


	public Session getSessao() {
		return sessao;
	}

	public void setSessao(Session sessao) {
		this.sessao = sessao;
	}

	@Override
	public List<Matricula> find(Object obj) {
		Matricula matricula = (Matricula) obj;
		this.sessao =  HibernateUtil.getSession().getCurrentSession();
		List<Matricula> lista;
		
		if(matricula.getAluno() != null) {
			if(matricula.getAluno().getIdAluno() != null) {
				if(matricula.getAluno().getIdAluno() != 0) {
					try {
						lista = this.sessao.createCriteria(Matricula.class)
								.createCriteria("aluno")
									.add(Restrictions.eq("idAluno", matricula.getAluno().getIdAluno()))
								.list();
						return lista;
					} catch (Exception e) {
						return null;
					}
				}
			}
			
			if(matricula.getAluno().getNome() != null) {
				if(!(matricula.getAluno().getNome().equals(""))) {
					try {
						lista = this.sessao.createCriteria(Matricula.class)
								.createCriteria("aluno")
									.add(Restrictions.like("nome", matricula.getAluno().getNome(), MatchMode.ANYWHERE).ignoreCase())
								.list();
						return lista;
					} catch (Exception e) {
						return null;
					}
				}
			}
		}
		try {
			lista = this.sessao.createCriteria(Matricula.class).list();
			return lista;
		} catch (Exception e) {
			return null;
		}
	}

	@Override
	public List<Matricula> findByPrimaryKey(Object obj) {
		this.sessao =  HibernateUtil.getSession().getCurrentSession();
		Matricula matricula = (Matricula) obj;
		try {
			List<Matricula> lista = this.sessao.createCriteria(Matricula.class)
									.add(Restrictions.eq("idMatricula", matricula.getIdMatricula()))
									.list();
			return lista;
		} catch (Exception e) {
			return null;
		}
	}
	
	@Override
	public List<Matricula> list() {	
		this.sessao =  HibernateUtil.getSession().getCurrentSession();
		try {
			List<Matricula> lista = this.sessao.createCriteria(Matricula.class).list();
			return lista;
		} catch (Exception e) {
			return null;
		}
	}	
}
